package com.cos.shop.dao.impl;

import com.cos.shop.dao.UserDao;
import com.cos.shop.entity.User;
import com.cos.shop.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: UserDaoImpl
 * Author: saber
 * Date:2022/9/16 18:34
 */
public class UserDaoImpl implements UserDao {

    private QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

    String select_sql = " select * from user ";

    @Override
    public int addUser(User user) throws SQLException {
        return qr.update("insert into user values(default,?,?,?,?,?,?,?)",
                user.getUname(),user.getUpassword(),
                user.getUemail(),user.getUsex(),
                user.getUstatus(),user.getUcode(),user.getUrole());
    }

    @Override
    public User getUserByUname(String uname) throws SQLException {
        return qr.query(select_sql+" where uname = ?",new BeanHandler<>(User.class),uname);
    }

    @Override
    public int changeUserStatus(int uid, int isActive) throws SQLException {
        return qr.update("update user set ustatus=? where uid = ?",
                isActive,uid);
    }

    @Override
    public User getUserByEmailAndCode(String email, String code) throws SQLException {
        return qr.query(select_sql+" where uemail = ? and ucode=?",
                new BeanHandler<>(User.class),email,code);
    }

}
